package com.example.train.common.config.security;

import com.example.train.common.config.security.filter.JwtAuthenticationTokenFilter;
import com.example.train.common.config.security.filter.PreventRequestReplayFilter;
import com.example.train.common.config.security.handler.RestAuthenticationEntryPoint;
import com.example.train.common.config.security.handler.RestfulAccessDeniedHandler;
import com.example.train.common.config.security.model.AuthUserDetail;
import com.example.train.model.SysAdmin;
import com.example.train.model.SysRole;
import com.example.train.service.SysAdminService;
import com.example.train.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.header.Header;
import org.springframework.security.web.header.writers.StaticHeadersWriter;

import java.util.Arrays;
import java.util.List;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Slf4j
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SysAdminService sysAdminService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;
    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;

    @Value("${api.headers.timestamp}")
    private String timestampHeader;

    @Value("${api.headers.sign}")
    private String signHeader;

    @Value("${settings.prevent-request-replay.enable}")
    private boolean preventRequestReplayEnable;

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {

        httpSecurity
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .csrf().disable()
                .headers().addHeaderWriter(new StaticHeadersWriter(Arrays.asList(
                    new Header("Access-control-Allow-Origin", "*"),
                    new Header("Access-Control-Expose-Headers", tokenHeader,timestampHeader,signHeader)
                )))
                .and()
                .formLogin().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS)
                .permitAll()
                .anyRequest()
                .authenticated()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
                    //注册设置动态资源管理器
                    @Override
                    public <O extends FilterSecurityInterceptor> O postProcess(O object) {
                        object.setSecurityMetadataSource(dynamicSecurityMetadataSource());
                        object.setAccessDecisionManager(dynamicAccessDecisionManager());
                        return object;
                    }
                });

        //csrf 参考 https://blog.csdn.net/u012888704/article/details/107408427
        //注意：cookie是基于域名来储存的。要放到测试服务器上或者本地localhost服务器上才会生效。cookie具有不同域名下储存不可共享的特性。单纯的本地一个html页面打开是无效的
        //https://ask.csdn.net/questions/643226

        httpSecurity.headers().cacheControl();
        // 添加JWT filter
        httpSecurity.addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);

        //可选择开启
        if (preventRequestReplayEnable) {
            httpSecurity.addFilterAfter(preventReplayFilter(), JwtAuthenticationTokenFilter.class);
        }
        //添加自定义未授权和未登录结果返回
        httpSecurity.exceptionHandling()
                .accessDeniedHandler(restfulAccessDeniedHandler)
                .authenticationEntryPoint(restAuthenticationEntryPoint);

    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers(ignoreUrlsConfig().getUrls().toArray(new String[ignoreUrlsConfig().getUrls().size()]));
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService())
                .passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public UserDetailsService userDetailsService() {
        //获取登录用户信息
        return username -> {
            SysAdmin admin = sysAdminService.selectByUsername(username);
            if (admin != null) {
                List<SysRole> roleList = sysRoleService.selectByAdminID(admin.getId());
                if (log.isDebugEnabled()) {
                    roleList.forEach(p->log.debug(p.toString()));
                }
                return new AuthUserDetail(admin,roleList);
            }
            throw new UsernameNotFoundException("用户名或密码错误");
        };
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter(){
        return new JwtAuthenticationTokenFilter();
    }

    @Bean
    public IgnoreUrlsConfig ignoreUrlsConfig(){
        return new IgnoreUrlsConfig();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public DynamicAccessDecisionManager dynamicAccessDecisionManager() {
        return new DynamicAccessDecisionManager();
    }

    @Bean
    public DynamicSecurityMetadataSource dynamicSecurityMetadataSource() {
        return new DynamicSecurityMetadataSource();
    }

    @Bean
    @ConditionalOnProperty(name = "settings.prevent-request-replay.enable",havingValue = "true")
    public PreventRequestReplayFilter preventReplayFilter() {
        return new PreventRequestReplayFilter();
    }
}
